<?php
/**
 * bs多规格sku商城系统
 * ============================================================================
 * 版权所有 2024-2099 wltx666.com，并保留所有权利。
 * 网站地址: https://wltx666.com
 * ============================================================================
 * Author: 草上飞
 * Email: wltx@alipay168.cn
 * QQ: 2719875001
 * Date: 2024/12/15
 * 描述:
 */

namespace app\result;

class ToolsResult extends BaseResult
{
    // 加密函数
    public static function encrypt($data, $key, $iv)
    {
        $encrypted = openssl_encrypt($data, "AES-128-CBC", $key, 0, $iv);
        return base64_encode($encrypted);
    }

    // 解密函数
    public static function decrypt($data, $key, $iv)
    {
        $decrypted = openssl_decrypt(base64_decode($data), "AES-256-CBC", $key, OPENSSL_RAW_DATA, base64_decode($iv));
        return $decrypted;
    }

    // 返回加密数据
    public static function encode_data($data)
    {
        $key = '您的密钥'; // 与前端相同的密钥
        $iv = '您的初始化向量'; // 与前端相同的IV
        $encryptedData = self:: encrypt(json_encode($data), $key, $iv);
        echo $encryptedData;
    }

    public static function ip_to_region($ip)
    {
        $ckey = 'ip2region' . $ip;
        if ($data = cache($ckey)) {
            return $data;
        }
        $key = config('tools.ip_key');
        //高德地图
        $url = "http://restapi.amap.com/v3/ip?ip={$ip}&output=json&key=$key";
        $result = json_decode(file_get_contents($url), true);
        if ($result['status'] == '1') {
            $arr['country'] = $result['country'] ?? '中国';
            $arr['province'] = $result['province'] ?: '未知';
            $arr['city'] = $result['city'] ?: '未知';
            cache($ckey, $arr, 86400);
            return $arr;
        }
        return ['country' => '未知', 'province' => '未知', 'city' => '未知'];
    }

    //使用ip2region查询
    public static function ip2region($ip)
    {
        if (!class_exists('\Ip2Region')) {
            return ['country' => '未知', 'province' => '未知', 'city' => '未知'];
        }
        $ip2region = new \Ip2Region();
        try {
            $geo = $ip2region->memorySearch($ip);
        } catch (\Exception $e) {
            bs_log($e->getMessage(), 'error', 'ip2regionv.log');
            return ['country' => '未知', 'province' => '未知', 'city' => '未知'];
        }
        $arr = [];
        if (stripos($geo['region'], '中国') === 0 && stripos($geo['region'], '内网') === false) {
            $region = array_values(array_filter(explode('|', $geo['region'])));//中国 广东 广州 电信
            if (empty($region[2])) {
                $arr = self::ip_to_region($ip);
            } else {
                $region[0] = $region[0] ?? '未知';
                $region[1] = $region[1] ?? '未知';
                $region[2] = $region[2] ?? '未知';
                [$arr['country'], $arr['province'], $arr['city']] = $region;
                empty($region['2']) && bs_log($region, 'ip2region', 'ip2regionv.log');
            }
        }

        return $arr;
    }

    /** 文件大小格式化
     * @param $size        int
     * @param $delimiter
     * @return string
     */
    public static function format_bytes($size, $delimiter = '')
    {
        $units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'];
        for ($i = 0; $size >= 1024 && $i < 5; $i++) {
            $size /= 1024;
        }
        return round($size, 2) . $delimiter . $units[$i];
    }

    //统计目录下面的目录大小
    public static function get_dir_size($dir)
    {
        $sizeResult = 0;
        if (!is_dir($dir)) {
            return $sizeResult;
        }
        $handle = opendir($dir);
        if ($handle === false) {
            return $sizeResult;
        }
        while (false !== ($FolderOrFile = readdir($handle))) {
            if ($FolderOrFile != "." && $FolderOrFile != "..") {
                $path = "$dir/$FolderOrFile";
                if (is_dir($path)) {
                    $sizeResult += self::get_dir_size($path);
                } else {
                    $fileSize = filesize($path);
                    if ($fileSize !== false) {
                        $sizeResult += $fileSize;
                    }
                }
            }
        }
        closedir($handle);
        return $sizeResult;
    }

    //删除目录和文件
    public static function del_dir($dir)
    {
        if (!is_dir($dir)) {
            return false;
        }
        $handle = opendir($dir);
        if ($handle === false) {
            return false;
        }
        while (false !== ($FolderOrFile = readdir($handle))) {
            if ($FolderOrFile != "." && $FolderOrFile != "..") {
                $path = "$dir/$FolderOrFile";
                if (is_dir($path)) {
                    self::del_dir($path);
                } else {
                    unlink($path);
                }
            }
        }
        closedir($handle);
        return rmdir($dir);
    }

}
